package com.binance.assetservice.web.service.impl;

import com.binance.assetservice.data.mapper.AssetMapper;
import com.binance.assetservice.data.mapper.ProductItemMapper;
import com.binance.assetservice.data.mapper.UserAssetDividendModelMapper;
import com.binance.assetservice.data.models.AssetItem;
import com.binance.assetservice.data.models.UserAssetDividendModel;
import com.binance.assetservice.vo.request.GetAssetByCodeRequest;
import com.binance.assetservice.vo.request.asset.UserAssetDividendRequest;
import com.binance.assetservice.vo.response.PagingResult;
import com.binance.assetservice.vo.response.asset.AssetResponse;
import com.binance.assetservice.vo.response.asset.GetAssetPicResponse;
import com.binance.assetservice.vo.response.asset.SymbolResponse;
import com.binance.assetservice.vo.response.asset.UserAssetDividendResponse;
import com.binance.assetservice.web.service.IAssetService;
import com.binance.master.utils.CopyBeanUtils;
import com.binance.master.utils.LanguageUtils;
import com.binance.master.utils.WebUtils;
import com.binance.sysconf.service.SysConfigVarCacheService;
import com.google.common.base.Converter;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.curator.shaded.com.google.common.collect.Lists;
import org.javasimon.aop.Monitored;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Monitored
@Service
public class AssetServiceImpl extends BaseServiceImpl implements IAssetService {

    @Autowired
    private AssetMapper assetMapper;
    @Autowired
    private ProductItemMapper productItemMapper;
    @Autowired
    private UserAssetDividendModelMapper userAssetDividendModelMapper;
    @Autowired
    private SysConfigVarCacheService sysConfigVarCacheService;

    @Override
    public AssetResponse getAssetByCode(GetAssetByCodeRequest request) {
        AssetItem assetItem =
                this.assetMapper.getAssetByCode(request.getAsset(), BooleanUtils.isTrue(request.getBackend()) ? 1 : 0);
        String language = LanguageUtils.getLanguage(WebUtils.getHttpServletRequest());
        if (assetItem != null) {
            if (BooleanUtils.isTrue(assetItem.getSameAddress())) {
                if (!"cn".equals(language)) {
                    assetItem.setAssetLabel(assetItem.getAssetLabelEn());
                }
            }
            AssetResponse assetResponse = CopyBeanUtils.copy(assetItem, AssetResponse.class);
            return assetResponse;
        }
        return null;
    }

    @Override
    public List<SymbolResponse> getSymbolByAsset(String baseAsset) {
        List<SymbolResponse> ret = null;
        List<Map<String,Object>> symbolMapList = productItemMapper.getByBaseAsset(baseAsset);
        if(!CollectionUtils.isEmpty(symbolMapList)){
            ret =  Lists.newArrayList();
            for(Map<String,Object> map: symbolMapList){
                SymbolResponse response =  CopyBeanUtils.copy(map, SymbolResponse.class);
                ret.add(response);
            }
        }
        return ret;
    }

    @Override
    public PagingResult<UserAssetDividendResponse> userAssetDividend(UserAssetDividendRequest body) throws Exception {
        String uid = body.getLoginUid();
        this.getCheckedUser(uid);
        if (body.getRows() == null || body.getRows() <= 0) {
            body.setRows(20);
        }
        if (body.getPage() == null || body.getPage() == 0) {
            body.setPage(1);
        }
        String lang = WebUtils.getHeader("lang");
        if (StringUtils.isBlank(lang)) {
            lang = "en";
        }
        Map<String, Object> map = Maps.newHashMap();
        map.put("lang", lang);
        map.put("uid", uid);
        map.put("email", body.getEmail());
        map.put("asset", body.getAsset());
        map.put("info", body.getInfo());
        map.put("startTime", body.getStartTime());
        map.put("endTime", body.getEndTime());

        map.put("page", (body.getPage() - 1) * body.getRows());
        map.put("offset", body.getRows());
        map.put("order", body.getOrder());
        map.put("sort", body.getSort());

        List<UserAssetDividendModel> rows = this.userAssetDividendModelMapper.getWebPageList(map);
        List<UserAssetDividendResponse> list = Lists.newArrayList();
        if (rows != null) {
            for (UserAssetDividendModel row : rows) {
                if (StringUtils.equals(uid, row.getUid())) {
                    row.setAmount(row.getAmount() == null ? BigDecimal.ZERO : row.getAmount());
                } else if (StringUtils.equals(uid, row.getFromUid())) {
                    row.setAmount(row.getAmount() == null ? BigDecimal.ZERO : row.getAmount().negate());
                }
                list.add(CopyBeanUtils.copy(row, UserAssetDividendResponse.class));
            }
        }
        long total = this.userAssetDividendModelMapper.getWebPageListCount(map);
        return new PagingResult<UserAssetDividendResponse>(list, total);

    }

    @Override
    public List<AssetResponse> getAllAsset() throws Exception {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("key", 1);
        List<AssetItem> items = this.assetMapper.selectAssetByMap(param);
        List<AssetResponse> list = Lists.newArrayList();
        if (items != null) {
            for (AssetItem item : items) {
                if (StringUtils.isNotBlank(item.getLogoUrl())) {
                    if (item.getLogoUrl().toLowerCase().startsWith("http")) {
                        item.setFullLogoUrl(item.getLogoUrl());
                    } else {
                        item.setFullLogoUrl(sysConfigVarCacheService.getValue("file_url") + item.getLogoUrl());
                    }
                }
                list.add(CopyBeanUtils.copy(item, AssetResponse.class));
            }
        }
        return list;
    }

    @Override
    public List<GetAssetPicResponse> getAssetPic() throws Exception {
        Map<String, Object> param = Maps.newHashMap();
        param.put("key", "1");
        List<GetAssetPicResponse> pic = Lists.transform(this.assetMapper.selectAssetByMap(param),
                new Converter<AssetItem, GetAssetPicResponse>() {
                    @Override
                    protected GetAssetPicResponse doForward(AssetItem assetModel) {
                        GetAssetPicResponse resp = new GetAssetPicResponse();
                        String logoUrl = assetModel.getLogoUrl();
                        if (StringUtils.isNotBlank(logoUrl)) {
                            if (logoUrl.toLowerCase().startsWith("http")) {
                                resp.setPic(logoUrl);
                            } else {
                                resp.setPic(sysConfigVarCacheService.getValue("file_url") + logoUrl);
                            }
                        }
                        resp.setAsset(assetModel.getAssetCode());
                        return resp;
                    }

                    @Override
                    protected AssetItem doBackward(GetAssetPicResponse map) {
                        return null;
                    }
                });
        return pic;
    }

}
